let siteinfo = require('../core/siteinfo.js');
// let _api_root = siteinfo.siteroot + siteinfo.project;
let _api_root = siteinfo.siteroot;
/**
 * 请求封装
 */
module.exports = {
	/**
	 * 正常的get请求
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} cb
	 */
	get(url, data) {
		return new Promise(function(resolve) {
			requset(url, data, "GET", false,resolve);
		})
	},

	/**
	 * 出现自定义loading的请求
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} cb
	 */
	GET(url, data) {
		return new Promise(function(resolve) {
			requset(url, data, "GET", true, resolve);
		})
	},
	/**
	 * 正常的post请求 loading
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} cb
	 */
	POST(url, data) {
		return new Promise(function(resolve) {
			requset(url, data, "POST", true, resolve);
		})
	},
	/**
	 * 没有加载的post
	 * @param {*} url 
	 * @param {*} data 
	 */
	post(url, data) {
		return new Promise(function(resolve) {
			requset(url, data, "POST", false, resolve);
		})
	},
	/**
	 * 
	 * @param {*} data 
	 */
  // 带loading动画
	uploadimg(url,data){
		return new Promise(function(resolve) {
			uploadFile(url,data,"post", true, resolve);
		})
	},
  // 不带loading动画
  UPLOADING(url,data){
    return new Promise(function(resolve) {
      uploadFile(url,data,"post", false, resolve);
    })
  }
}


function requset(url, data, method, isLoading,cb) {
	if (isLoading) {
		wx.showLoading({
			title: '加载中...',
		})
	}
	var URL = "";
	if (url.indexOf('http://') !== 0) {
		URL = _api_root + url
	} else {
		URL = url
	};
	wx.request({
		url: URL,
		data: data || {},
		method: method || "GET",
		header: {
      'Content-Type': 'application/json',
      // "Authorization": `Bearer ${wx.getStorageSync("token")}` || ''
		},
		success: res => {
      // console.log(res,"res");
      if (res.data.code === 200) {
        // console.log(res,"res");
        if (isLoading) {
					wx.hideLoading();
        };
      } else if(res.data.code === 401){ 
        // 没有登录
        // 需要userId的接口
        wx.hideLoading(); 
        wx.showModal({
          title: "提示",
          content: "当前用户未授权登录，请前往授权页进行登录",
          success: (res) => {
            if (res.confirm) {
              //跳转至登录页面
              wx.navigateTo({
                url: '/pages/login/login',
              })
            } else {
              // wx.navigateBack()
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          }
        });
      }else {
        wx.showToast({
					title: res.data.msg,
					mask: true,
					icon: "none"
        })
			};
			if (isLoading) {
				wx.hideLoading();
      };
      return typeof cb == "function" && cb(res.data);
		},
		fail: res => {
			if (isLoading) {
				wx.hideLoading();
			};
			wx.showToast({
        title: '网络出错,请刷新后重试',
        icon: 'none',
        duration: 1000,
        mask:true
      })
		}
	})
}


function uploadFile(url,data,method,isLoading,cb){
  if (isLoading) {
		wx.showLoading({
			title: '上传中...',
		})
	}
  wx.uploadFile({
    url: _api_root + url, // 上传的服务器接口地址
    filePath: data,
    header: {
      "Content-Type": "multipart/form-data",        
    },
    name: 'file', //上传的所需字段，后端提供
    formData: {
      'dir': "goods",
    },
    timeout:60000000,
    success: (res) => {
      // 上传完成操作
      const data = JSON.parse(res.data)
      // console.log(data,"res.data.code");
      if (data.code === 200) {
        if (isLoading) {
					wx.hideLoading();
        };
      }
      // resolve({
      //   data: data
      // })
      // return cb
      return typeof cb == "function" && cb(data);
      
    },
    fail: (err) => {
      if (isLoading) {
        wx.hideLoading();
      };
      //上传失败：修改pedding为reject
      console.log("访问接口失败", err);
      wx.showToast({
        title: "网络出错,上传失败",
        icon: 'none',
        duration: 1000
      });
      // reject(err)
    }
  });
}

